package com.me.extend.thread

import java.util.concurrent.*
import java.util.concurrent.Executors

/**
 * 各种线程池集中管理调用
 */
object Executors {

    private val codeCount = Runtime.getRuntime().availableProcessors()

    private val cachedThreadPool: ExecutorService by lazy {
        ThreadPoolExecutor(0, codeCount * 2, 60L, TimeUnit.SECONDS, SynchronousQueue())
    }
    private val ioThreadPool: ExecutorService by lazy {
        ThreadPoolExecutor(
            codeCount,
            codeCount,
            0L,
            TimeUnit.MILLISECONDS,
            LinkedBlockingQueue()
        )
    }
    private val singleThreadPool: ExecutorService by lazy {
        Executors.newSingleThreadExecutor()
    }

    fun singleThread(block: () -> Unit) {
        singleThreadPool.execute(block)
    }

    fun singleThread(runnable: Runnable) {
        singleThreadPool.submit(runnable)
    }

    fun ioThread(block: () -> Unit) {
        ioThreadPool.execute(block)
    }

    fun ioThread(runnable: Runnable) {
        ioThreadPool.submit(runnable)
    }

    fun cachedThread(block: () -> Unit) {
        cachedThreadPool.execute(block)
    }

    fun cachedThread(runnable: Runnable) {
        cachedThreadPool.submit(runnable)
    }
}